#include "rotate.h"

word ror(word value, int shift_bits)
{
	shift_bits %= 32;
	if(shift_bits == 0 )
		return value;

	word lowest_bits = value << (32 - shift_bits);
	word result = value >> shift_bits;
	result ^= lowest_bits;

	return result;
}

word rol(word value, int shift_bits)
{
	shift_bits %= 32;
	if(shift_bits == 0 )
		return value;

	word highest_bits = value >> (32 - shift_bits);
	word result = value << shift_bits;
	result ^= highest_bits;

	return result;
}

byte ror4(byte value, int shift_bits)
{
	static const byte masks[] = {0x1, 0x3, 0x7};

	shift_bits = shift_bits % 4;
	if(shift_bits == 0)
		return value;

	byte mask = masks[shift_bits - 1];
	byte lowest_bits= value & mask;
	byte result = value >> (shift_bits);
	result ^= lowest_bits << (4 - shift_bits);

	return result;

}

#include <stdio.h>
#include <assert.h>
void test_rol()
{
	printf("Start testing rol......\n");

	assert( rol(0x0,0) == 0);
	assert( rol(0xf3,0) == 0xf3);

	assert( rol(0x0,1) == 0);
	assert( rol(0x80000000,1) == 0x00000001);
	assert( rol(0xfffffffe,1) == 0xfffffffd);

	assert( rol(0xdf39807e,3) == 0xf9cc03f6);

//	printf("%x", rol(0x4d1b4aaa,1));

	printf("Test rol complete!\n");
}

void test_ror()
{
	printf("Start testing ror........\n");

	assert( ror(0x0, 0) == 0);
	assert( ror(0xf3, 0) == 0xf3);

	assert( ror(0x0,1) == 0);
	assert( ror(0x01,1) == 0x80000000);
	assert( ror(0xefffffff,1) == 0xf7ffffff);

	assert( ror(0xdf39807e,3) == 0xdbe7300f);

//	printf("%x\n", ror(0x871b9549,1));

	printf("Test ror complete!\n");
}

void test_ror4()
{
	printf("Start testing ror4..........\n");
	assert( ror4(0,0) == 0);
	assert( ror4(1,0) == 1);
	assert( ror4(1,4) == 1);

	assert( ror4(0,1) == 0);
	assert( ror4(1,1) == 8);
	assert( ror4(2,1) == 1);
	assert( ror4(4,1) == 2);
	assert( ror4(8,1) == 4);

	assert( ror4(3,1) == 9);
	assert( ror4(6,1) == 3);
	assert( ror4(7,1) == 11);
	assert( ror4(15,1) == 15);
	printf("Test ror4 has completed!\n");
}
